package access.spg.android.com.accessibilitytest;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.GestureDescription;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import java.util.List;
import java.util.Random;

@RequiresApi(api = Build.VERSION_CODES.O)
public class ReadArticleService extends AccessibilityService {
    private static String tag="AccessibilityJavaService";

    //dftt          com.songheng.eastnews:id/t8
    //kuaikandian   com.yuncheapp.android.pearl:id/root
    private static String ITEM_ID="com.jifen.qukan:id/y4";

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.d(tag,"onServiceConnected");
//        AccessibilityServiceInfo info=new AccessibilityServiceInfo();
//        info.packageNames=new String[]{"com.jifen.qukan"};
//        setServiceInfo(info);
//        searchNode();
    }

    @Override
    public void onInterrupt() {
        Log.d(tag,"onInterrupt");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(tag,"onUnbind");
        return super.onUnbind(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        switch (event.getEventType())
        {
            case AccessibilityEvent.TYPE_VIEW_SCROLLED:
//                scrollUp(false,-1);
                break;
            case AccessibilityEvent.TYPE_VIEW_CLICKED:
                try
                {
                    if(event.getText().get(0).equals("财经"))
                    {
                        readNews();
                    }
                }catch (Exception e){

                }
                break;
        }
    }


    private void readNews()
    {
        Log.e(tag, "============开始readNews===============" );

        for(int i=0;i<=2;i++)
        {
            scrollUp(true,1,0,-1);
        }

        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        List<AccessibilityNodeInfo> list=rootNode.findAccessibilityNodeInfosByViewId(ITEM_ID);
        if(list==null || list.size()==0)
        {
            Log.e(tag, "============没有相关id===============" );
        }
        for(int i=0;i<list.size();i++)
        {
            try
            {
                AccessibilityNodeInfo node=list.get(i);
                if(onClickByNodeLocation(node))
                {
                    readNewsDetail();
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                }else
                {
                    Thread.sleep(500);
                }

            }catch (Exception e){}
        }
        readNews();

    }


    private boolean onClickByNodeLocation(AccessibilityNodeInfo node)
    {
        if(node==null)
        {
            Log.e(tag, "============元素为空，无法点击===============" );
            return false;
        }

        Rect rect=new Rect();
        node.getBoundsInScreen(rect);
        int y=rect.top+20;
        int x=rect.left+20;
        Log.e(tag, "x=="+x );
        Log.e(tag, "y=="+y );
        Path path = new Path();
        path.moveTo(x, y);
        path.lineTo(x, y);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gestureDescription = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 500L, 800L,false))
                .build();

        dispatchGesture(gestureDescription, new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.e(tag, "============List onCompleted===============" );
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.e(tag, "============List onCancelled==============="+gestureDescription.getStroke(0).toString());
            }
        }, new Handler(Looper.getMainLooper()));

//        if(node.isClickable())
//        {
//            node.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
//            node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
//            Log.e(tag, "============成功点击===============" );
//            return true;
//        }
//        Log.e(tag, "============点击失败===============" );

        return true;
    }

    private void readNewsDetail()
    {
        Random ra =new Random();
        int tmp=ra.nextInt(5)+1;
        scrollUp(true,tmp,0,10);
    }




    /**
     * 向上翻页
     *
     * @param loop 是否在循环中
     *
     * @param limit 是否限制循环次数  无限循环 -1
     * @param nowTime 已经循环了几次  传 0
     * */
    private void scrollUp(boolean loop,int limit,int nowTime,int offsetTime)
    {
        Log.e(tag, "=====循环次数 "+limit+"=====已循环 "+nowTime);
//        if(!start)
//        {
//            start=true;
//        }else
//        {
            if(!loop)
                return;
            if(limit!=-1 && limit==nowTime)
                return;
//        }


        try {//滞留
            Random ra =new Random();
            int tmp;
            if(offsetTime!=-1)
            {
                tmp=ra.nextInt(offsetTime)+5;
            }else
            {
                tmp=2;
            }
            Log.e(tag, "============scrollUp wait "+tmp+"s===============" );
            Thread.sleep(tmp*1000);

            Toast.makeText(this,"时间："+tmp,Toast.LENGTH_SHORT).show();

            GestureDescription.Builder builder = new GestureDescription.Builder();
             Path path = new Path();
             float y1 = MyUtil.getWindowHeight(this)*0.8f;
             float y2 = MyUtil.getWindowHeight(this)*0.1f;
             float x =MyUtil.getWindowWidth(this)/2f;
             path.moveTo(x, y1);
             path.lineTo(x, y2);
             GestureDescription gestureDescription = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 200L, 800L,false))
                .build();

             dispatchGesture(gestureDescription, new AccessibilityService.GestureResultCallback() {
                 @Override
                 public void onCompleted(GestureDescription gestureDescription) {
                     super.onCompleted(gestureDescription);
                     Log.e(tag, "============Swipe onCompleted===============" );
                 }

                 @Override
                 public void onCancelled(GestureDescription gestureDescription) {
                     super.onCancelled(gestureDescription);
                     Log.e(tag, "============Swipe onCancelled===============");
                 }
             }, new Handler(Looper.getMainLooper()));

            nowTime++;
            scrollUp(true,limit,nowTime,offsetTime);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     }




    /**
     * 循环遍历窗口节点
     */
    private void searchNode() {
        AccessibilityNodeInfo rowNode = getRootInActiveWindow();
        if (rowNode != null) {
            for (int i = 0; i < rowNode.getChildCount(); i++) {
                if (rowNode.getChild(i) != null) {
                    recycle(rowNode.getChild(i));
                }
            }
        }
    }
    public static void recycle(AccessibilityNodeInfo info) {
        if (info.getChildCount() == 0) {
            Log.i(tag, "child widget:" + info.getClassName());
            Log.i(tag, "showDialog:" + info.canOpenPopup());
            Log.i(tag, "Text：" + info.getText());
            Log.i(tag, "windowId:" + info.getWindowId());
        } else {
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    recycle(info.getChild(i));
                }
            }
        }
    }



}
